# -*- coding: utf-8 -*-
import wx
import wx.xrc
import wx.adv
import gettext
from wordcloud import WordCloud
_ = gettext.gettext
background_color = 'white'
font_path = '0.ttf'
max_words = 150
max_font_size = 72
width = 350
height = 350
colormap = 'viridis'
img = None
min_font_size = 20
stopwords = open('stopword.txt', encoding='utf-8').read()
# 修改 wordcloudiniter 函数，使其返回 WordCloud 实例
def wordcloudiniter():
    return WordCloud(
        background_color=background_color,
        font_path=font_path,
        max_words=max_words,
        max_font_size=max_font_size,
        width=width,
        height=height,
        colormap=colormap,
		min_font_size=min_font_size,
		stopwords=stopwords
    )
class MainFrame ( wx.Frame ):
	def __init__(self, parent):
		wx.Frame.__init__ (self, parent, id = wx.ID_ANY, title = "词云生成器", pos = wx.DefaultPosition,
						   size = wx.Size( 900,450 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL)
		self.SetIcon(wx.Icon('q.ico', wx.BITMAP_TYPE_ICO))
		self.SetSizeHints(wx.DefaultSize, wx.DefaultSize)
		self.SetBackgroundColour(wx.Colour( 255, 255, 255 ))
		mainsizer = wx.BoxSizer(wx.HORIZONTAL)
		btnsizer = wx.GridSizer(0, 2, 0, 0)
		self.beijing = wx.StaticText(self, wx.ID_ANY, _(u"背景颜色"), wx.DefaultPosition, wx.DefaultSize, 0)
		self.beijing.Wrap(-1)
		btnsizer.Add(self.beijing, 0, wx.ALL, 5)
		beijingchooseChoices = [ _(u"白色"), _(u"绿色"), _(u"黄色"), _(u"蓝色"),
								 _(u"红色"), _(u"黑色"), _(u"紫色") ]
		self.beijingchoose = wx.Choice(self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 150,50 ),
									   beijingchooseChoices, 0)
		self.beijingchoose.SetSelection(0)
		btnsizer.Add(self.beijingchoose, 0, wx.ALL, 5)
		self.sexi = wx.StaticText(self, wx.ID_ANY, _(u"色系"), wx.DefaultPosition, wx.DefaultSize, 0)
		self.sexi.Wrap(-1)
		btnsizer.Add(self.sexi, 0, wx.ALL, 5)
		sexichooseChoices = [ _(u"默认"), _(u"热力"), _(u"熔岩"), _(u"色盲系") ]
		self.sexichoose = wx.Choice(self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 150,50 ),
									sexichooseChoices, 0)
		self.sexichoose.SetSelection(0)
		btnsizer.Add(self.sexichoose, 0, wx.ALL, 5)
		self.ziti = wx.StaticText(self, wx.ID_ANY, _(u"字体"), wx.DefaultPosition, wx.DefaultSize, 0)
		self.ziti.Wrap(-1)
		btnsizer.Add(self.ziti, 0, wx.ALL, 5)
		zitichooseChoices = [ _(u"宋体"), _(u"黑体"), _(u"行书"), _(u"行草"), _(u"行楷"),
							  _(u"刺猬艺术体"), _(u"毛笔手书体") ]
		self.zitichoose = wx.Choice(self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 150,50 ),
									zitichooseChoices, 0)
		self.zitichoose.SetSelection(0)
		btnsizer.Add(self.zitichoose, 0, wx.ALL, 5)
		self.daoru = wx.StaticText(self, wx.ID_ANY, _(u"导入"), wx.DefaultPosition,
								   wx.DefaultSize, 0)
		self.daoru.Wrap(-1)
		btnsizer.Add(self.daoru, 0, wx.ALL, 5)
		self.daorubtn = wx.Button(self, wx.ID_ANY, _(u"路径..."),
								  wx.DefaultPosition, wx.Size( 150,50 ), 0)
		btnsizer.Add(self.daorubtn, 0, wx.ALL, 5)
		self.daochu = wx.StaticText(self, wx.ID_ANY, _(u"另存为"),
									wx.DefaultPosition, wx.DefaultSize, 0)
		self.daochu.Wrap(-1)
		btnsizer.Add(self.daochu, 0, wx.ALL, 5)
		self.save = wx.Button(self, wx.ID_ANY, _(u"路径..."),
							  wx.DefaultPosition, wx.Size( 150,50 ), 0)
		btnsizer.Add(self.save, 0, wx.ALL, 5)
		mainsizer.Add(btnsizer, 3, wx.EXPAND, 5)
		inputsizer = wx.BoxSizer(wx.VERTICAL)
		self.shuru = wx.StaticText(self, wx.ID_ANY, _(u"请输入文本："),
								   wx.DefaultPosition, wx.DefaultSize, 0)
		self.shuru.Wrap(-1)
		inputsizer.Add(self.shuru, 0, wx.ALL, 5)
		self.inputtext = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,
									 wx.Size( 200,350 ), wx.TE_MULTILINE | wx.TE_WORDWRAP)
		inputsizer.Add(self.inputtext, 0, wx.ALL, 5)
		mainsizer.Add(inputsizer, 2, wx.EXPAND, 5)
		showsizer = wx.BoxSizer(wx.VERTICAL)
		self.show = wx.adv.AnimationCtrl(self, wx.ID_ANY, wx.adv.NullAnimation, wx.DefaultPosition,
										 wx.Size( 350,350 ), wx.adv.AC_DEFAULT_STYLE)
		self.show.SetInactiveBitmap(wx.Bitmap( u"0.jpg", wx.BITMAP_TYPE_ANY ))
		showsizer.Add(self.show, 10, wx.ALL, 5)
		bSizer6 = wx.BoxSizer(wx.HORIZONTAL)
		self.show1 = wx.StaticText(self, wx.ID_ANY, _(u"可能会有布局错误导致显示不\n全或变形，导出后问题会解决\n"),
								   wx.DefaultPosition, wx.DefaultSize, 0)
		self.show1.Wrap(-1)
		bSizer6.Add(self.show1, 0, wx.ALL, 5)
		self.make = wx.Button(self, wx.ID_ANY, _(u"生成"), wx.DefaultPosition, wx.DefaultSize, 0)
		bSizer6.Add(self.make, 0, wx.ALL, 5)
		showsizer.Add(bSizer6, 1, wx.EXPAND, 5)
		mainsizer.Add(showsizer, 4, wx.EXPAND, 5)
		self.SetSizer( mainsizer )
		self.Layout()
		self.Centre(wx.BOTH)
		# Connect Events
		self.beijingchoose.Bind(wx.EVT_CHOICE, self.Beijing)
		self.sexichoose.Bind(wx.EVT_CHOICE, self.Sexi)
		self.zitichoose.Bind(wx.EVT_CHOICE, self.Ziti)
		self.daorubtn.Bind(wx.EVT_BUTTON, self.Input)
		self.save.Bind(wx.EVT_BUTTON, self.Save)
		self.make.Bind(wx.EVT_BUTTON, self.Make)
	# Virtual event handlers, overide them in your derived class
	def Beijing( self, event ):
		value = event.GetEventObject()
		global background_color
		background_color = 'white'
		if value.GetSelection() == 0:
			background_color = 'white'
		elif value.GetSelection() == 1:
			background_color = 'green'
		elif value.GetSelection() == 2:
			background_color = 'yellow'
		elif value.GetSelection() == 3:
			background_color = 'blue'
		elif value.GetSelection() == 4:
			background_color = 'red'
		elif value.GetSelection() == 5:
			background_color = 'black'
		elif value.GetSelection() == 6:
			background_color = 'purple'
	def Sexi( self, event ):
		value = event.GetEventObject()
		global colormap
		colormap = 'viridis'
		if value.GetSelection() == 0:
			colormap = 'viridis'
		elif value.GetSelection() == 1:
			colormap = 'plasma'
		elif value.GetSelection() == 2:
			colormap = 'magma'
		elif value.GetSelection() == 3:
			colormap = 'cividis'

	def Ziti( self, event ):
		value = event.GetEventObject()
		global font_path
		font_path = '0.ttf'
		if value.GetSelection() == 0:
			font_path = '0.ttf'
		elif value.GetSelection() == 1:
			font_path = '1.ttf'
		elif value.GetSelection() == 2:
			font_path = '2.ttf'
		elif value.GetSelection() == 3:
			font_path = '3.ttf'
		elif value.GetSelection() == 4:
			font_path = '6.ttf'
		elif value.GetSelection() == 5:
			font_path = '5.ttf'
		elif value.GetSelection() == 6:
			font_path = '4.ttf'

	def Input( self, event ):
		# 修改此处，移除结尾多余的 |
		wildcard = "文本文档 (*.txt)|*.txt"
		dialog = wx.FileDialog(
			self,
			message="导入文本文件",
			wildcard=wildcard,
			style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST
		)
		if dialog.ShowModal() == wx.ID_CANCEL:
			return  # the user changed their mind
		path = dialog.GetPath()
		with open(path, 'r', encoding='utf-8') as f:
			text = f.read()
			self.inputtext.SetValue(text)
	def Save( self, event ):
		wildcard = "图片 (*.png)|*.png"
		dialog = wx.FileDialog(
			self,
			message="另存为图片文件",
			wildcard=wildcard,
			style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT
		)
		if dialog.ShowModal() == wx.ID_OK:
			path = dialog.GetPath()
			# 检查路径是否有扩展名，如果没有则添加 .png
			import os
			if not os.path.splitext(path)[1]:
				path += '.png'
			if img is not None:
				try:
					img.save(path)
				except Exception as e:
					wx.MessageBox(f"保存图片时出错: {e}", "错误", wx.OK | wx.ICON_ERROR)
			else:
				wx.MessageBox("请先生成词云", "错误", wx.OK | wx.ICON_ERROR)
		dialog.Destroy()
	def Make( self, event ):
		global wc
		global img
		# 调用 wordcloudiniter 函数并将返回值赋给 wc
		wc = wordcloudiniter()
		wc.generate(self.inputtext.GetValue())
		img = wc.to_image()

		# 将 PIL Image 转换为 wx.Bitmap
		if img.mode == 'RGBA':
		    img = img.convert('RGB')
		wx_image = wx.Image(img.size[0], img.size[1], img.tobytes())
		wx_bitmap = wx_image.ConvertToBitmap()

		self.show.SetInactiveBitmap(wx_bitmap)


if __name__ == '__main__':
	app = wx.App()
	frm = MainFrame(None)
	frm.Show()
	app.MainLoop()

